/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.widgets;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;

/**
 *
 * @author dpatchett
 */
public class TimeTextField extends JFormattedTextField
        implements FocusListener, Runnable {

    private final static TimeFormatterFactory
            timeFormatterFactory = new TimeFormatterFactory();

    @SuppressWarnings("LeakingThisInConstructor")
    public TimeTextField() {
        super(timeFormatterFactory);
        this.addFocusListener(this);
    }

    private Double oldTime;

    @Override
    protected void invalidEdit() {
        setValue(oldTime);
    }

    @Override
    public void setText(String t) {
        super.setText(t);
        oldTime = getTimeAsDouble();
    }

    public void focusGained(FocusEvent e) {
        java.awt.EventQueue.invokeLater(new Thread(this));
    }

    public void focusLost(FocusEvent e) {
        try {
            if (getFormatter().stringToValue(getText()) == null) {
                setValue(oldTime);
            }
        } catch (ParseException ex) {
            Logger.getLogger(TimeTextField.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Object getTimeValue() {
        
        try {
            if (getText() == null || getText().length() == 0) {
                return null;
            } else {
                return timeFormatterFactory.getFormatter(this).stringToValue(getText());
            }

        } catch (ParseException ex) {
            Logger.getLogger(TimeTextField.class.getName()).log(Level.SEVERE, null, ex);
            return (Double)0.0;
        }
    }

    // This is a dummy value to hopefully allow property binding
    private Double valueAsDouble;

    public Double getTimeAsDouble() {
        return (Double)getTimeValue();
    }

    public void setTimeAsDouble(Double value) {
        setValue(value);
    }

    public void run() {
        this.selectAll();
    }
}
